package com.yimu.lib.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.yanzhenjie.permission.AndPermission;
import com.yimu.lib.Receiver.AndroidNotify;
import com.yimu.lib.Receiver.NetBroadcastReceiver;
import com.yimu.lib.util.MyLogger;
import com.yimu.lib.util.NetUtil;
import java.util.ArrayList;
import java.util.List;
/**
 * 描述：BaseActivity
 * 创建者：  Churck
 * 创建时间：16/6/8 16:10
 * 修改者： Churck
 * 修改时间：16/6/8 16:10
 * 版 本：v1.0
 */
public  abstract class BaseActivity extends AppCompatActivity implements NetBroadcastReceiver.NetEvevt {
    public static NetBroadcastReceiver.NetEvevt evevt;
    private static int activity_count;//Activity计数
    private static boolean firstActivity = true;//第一个Activity启动时不调用#applicationWillEnterForeground
    private List<String> actionList;
    private BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        evevt = this;
        inspectNet();
           MyLogger.d("======onCreate=======");
           BaseApplication.getInstance().addActivity(this);
           setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


    }
    /**
     * 初始化时判断有没有网络
     */
    public boolean inspectNet() {
        int netModile = NetUtil.getNetWrokState(BaseActivity.this);
        MyLogger.d("网络状态"+netModile);
        return isNetConnect(netModile);
    }
    @Override
    public void onNetChange(int netModile) {
        MyLogger.d("通知回调网络状态"+netModile);
        isNetConnect(netModile);
    }
    /**
     * 判断有无网络 。
     * @return true 有网, false 没有网络.
     */
    private boolean isNetConnect(int netModile) {
        closenetbuilder();
        if (netModile == 1) {
            return true;
        } else if (netModile == 0) {
            return true;
        } else if (netModile == -1) {
            openNetworkSetting(this);
            return false;
        }
        return false;
    }
    AlertDialog netDialog=null;
    private void closenetbuilder(){
        if (null!=netDialog&&netDialog.isShowing()){
            netDialog.cancel();
        }
    }
    /**
     * 打开网络设置界面
     * @param context
     */
    private  void openNetworkSetting(final Context context){
        //提示对话框

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    openSetting();
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        netDialog =builder .create();
        netDialog.setCanceledOnTouchOutside(false);
        netDialog.setCancelable(false);
        netDialog .show();
    }

    /**
     * 打开wife设置
     */
    private  void openSetting() {
        Intent intent = new Intent("/");
        ComponentName cm = new ComponentName("com.android.settings",
                "com.android.settings.WirelessSettings");
        intent.setComponent(cm);
        intent.setAction("android.intent.action.VIEW");

    }
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        // 这个Activity中没有Fragment，这句话可以注释。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
  }

    /**
     * 跳转权限设置
     */
    public void jumpMessage(){
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

//********************** END Android M Permission ****************************************
    /**
     * 界面跳转
     */
    public final void startActivity(Class<? extends Activity> activity) {
        startActivity(activity,false);
    }
    public final void startActivity(Class<? extends Activity> activity,boolean isFinish) {
        startActivity(new Intent(this, activity));
        if (isFinish)
            finish();
    }
    @Override
    protected void onStart() {
        MyLogger.d("=====onStart=====");
        super.onStart();
        activity_count++;
        if (activity_count == 1 && false == firstActivity) {
            MyLogger.d("applicationWillEnterForeground: %s", this.getClass().getCanonicalName());
            applicationWillEnterForeground();
        }

        firstActivity = false;
    }
    @Override
    protected void onResume() {
        MyLogger.d("=====onResume====");

        super.onResume();
    }
    @Override
    protected void onPause() {
        MyLogger.d("======onPause======");
        super.onPause();
    }
    @Override
    protected void onStop() {
        MyLogger.d("=====onStop=====");
        super.onStop();
        activity_count--;
        if (activity_count == 0) {
            MyLogger.d("applicationWillEnterBackground: %s", this.getClass().getCanonicalName());
            applicationWillEnterBackground();
        }

    }
    /**
     * 前台进入后台回调
     */
    public void applicationWillEnterBackground() {
        MyLogger.d("=====前台进入后台回调=====");
    }
    /**
     * 后台进入前台回调
     */
    public void applicationWillEnterForeground(){
        MyLogger.d("=====后台进入前台回调=====");
    }
    protected final void registerReceiver(List<String> actions) {
        createReceiver();
        actionList.addAll(actions);
        AndroidNotify.registerReceiver(receiver, actionList);
    }

    public final void unregisterReceiver(List<String> actions) {
        if (actionList == null)
            return;
        actionList.removeAll(actions);
        AndroidNotify.registerReceiver(receiver, actionList);
    }

    private void createReceiver() {
        if (receiver != null)
            return;
        actionList = new ArrayList<>();
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (actionList.contains(action)) {
                    BaseActivity.this.onReceive(action, intent);
                }
            }
        };
    }

    /**
     * 接受本地广播
     * @param action 广播类型
     * @param intent 参数
     */
    protected void onReceive(String action, Intent intent) {
    }

    /**
     * 设置全屏
     */
    protected void setFullScreen() {
        Window window = getWindow();
        //设置无标题
        window.requestFeature(Window.FEATURE_NO_TITLE);
        //设置全屏
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //隐藏下方导航栏
        WindowManager.LayoutParams params = window.getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        window.setAttributes(params);
    }
    @Override
    protected void onDestroy() {
        MyLogger.d("======onDestroy=======");
        super.onDestroy();
        AndroidNotify.unregisterReceiver(receiver);
        BaseApplication.getInstance().removeActivity(this);

    }
}
